# encoding: utf-8
""" 
@version: v1.0 
@author: autumner 
@license: Apache Licence  
@contact: 18322313385@163.com 
@site:  
@software: PyCharm 
@file: class_weakref1.py 
@time: 2019/6/27 16:37
"""
'''
创建缓存实例
创建工厂函数
'''

import weakref

class CacheSpamManager:
    def __init__(self):
        self._cache = weakref.WeakValueDictionary()

    def get_spam(self, name):
        if name not in self._cache:
            temp = Spam2._new(name)
            self._cache[name] = temp
        else:
            temp = self._cache[name]

        return temp

    def clear(self):
        self._cache.clear()


class Spam:
    manager = CacheSpamManager()
    def __init__(self, name):
        self.name = name

    def get_spam(name):
        return Spam.manager.get_spam(name)


class Spam2:
    def __init__(self, *args, **kwargs):
        raise RuntimeError("Can't instantiate directly")

    # Alternate constructor
    @classmethod
    def _new(cls, name):
        self = cls.__new__(cls)
        self.name = name
        return self

# Example use

a = Spam('foo')
b = Spam('foo')
c = Spam('bar')
print(a is b)
print(a is c)